import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";

Vue.use(Vuex)

export default new Vuex.Store({
  state () {
    return {
      list: [],
      checkedAll: false,
      // 总金额
      total: 0,
      // 总件数
      totalCounts:0
    }
  },
  actions: {
    async initCartList(context) {
      // 调用 axios 的 get 方法，请求列表数据
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      // 只要请求回来的数据，在页面渲染期间要用到，则必须转存到 data 中
      if (res.status === 200) {
        context.commit('INIT_LIST',res.list)
      }
    },
  },
  mutations: {
    INIT_LIST(state,value){
      state.list = value
      console.log(state.list)
    },
    CHANGE_CHECK(state, value) {
      state.list.forEach(item => {
        if (item.id == value.id) {
           console.log(value)
          item.goods_state = value.state
        }
      })
      state.checkedAll = state.list.every(item => item.goods_state)
    },
    CHANGE_CHECKALL(state, value) {
      // state.checkedAll = value
      state.list.forEach(item => item.goods_state = value )
    },
    HANDLE_ADD(state, value) {
      state.list.forEach(item => {
        if (item.id === value.id) {
          item.goods_count = value.number
        }
      })
    },
    // 获得总件数 总金额
    GETTOTAL(state) {
      state.totalCounts = state.list.reduce((pre, cur) => {
        return pre + (cur.goods_state ? cur.goods_count : 0)
      }, 0),
      state.total = state.list.reduce((pre, cur) => {
        return pre + (cur.goods_state ? cur.goods_count * cur.goods_price : 0)
      },0)
    }
  }
})
